//
//  DownloadImageOperation.m
//  多线程编程
//
//  Created by GR on 2017/7/16.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "DownloadImageOperation.h"
#import <SDWebImageManager.h>

@interface DownloadImageOperation () {
    BOOL        executing;  // 执行中
    BOOL        finished;   // 已完成
}
@property (copy, nonatomic) NSString *imageUrl;
@end

@implementation DownloadImageOperation

- (instancetype)initWithImageUrl:(NSString *)imageUrl {
    if (self = [super init]) {
        self.imageUrl = imageUrl;
        executing = NO;
        finished = NO;
    }
    return self;
}

- (void)start {
    if ([self isCancelled]) {
        [self willChangeValueForKey:@"isFinished"];
        finished = YES;
        [self didChangeValueForKey:@"isFinished"];
        return;
    }
    
    [self willChangeValueForKey:@"isExecuting"];
    [self main];
    executing = YES;
    [self didChangeValueForKey:@"isExecuting"];
}

- (void)main {
    
    @try {
        @autoreleasepool {
            if ([self isCancelled]) {
                [self completeOperation];
                return;
            }
            
            [SDWebImageManager.sharedManager downloadImageWithURL:[NSURL URLWithString:self.imageUrl] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                self.image = image;
                
                [self completeOperation];
            }];

        }
    } @catch (NSException *exception) {
        NSLog(@"exception - %@", exception);
    }
    
    
}


- (BOOL)isAsynchronous {
    return YES;
}

- (BOOL)isExecuting {
    return executing;
}

- (BOOL)isFinished {
    return finished;
}

- (void)completeOperation {
    [self willChangeValueForKey:@"isFinished"];
    [self willChangeValueForKey:@"isExecuting"];
    
    executing = NO;
    finished = YES;
    
    [self didChangeValueForKey:@"isExecuting"];
    [self didChangeValueForKey:@"isFinished"];
}
@end
